<template>
  <div class="dashboard-container">
    <!-- Header Section -->
    <div class="dashboard-header">
      <h1 class="dashboard-title">业务数据概览</h1>
      <div class="dashboard-actions">
        <el-button type="primary" icon="el-icon-refresh" size="small" @click="refreshData">刷新数据</el-button>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          size="small"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
          :disabled="true"
          class="date-filter">
        </el-date-picker>
      </div>
    </div>

    <!-- Stats Cards Row -->
    <div class="stats-grid">
      <!-- 客户总数 Card -->
      <div class="stat-card stat-blue animate__animated animate__fadeInUp">
        <div class="stat-trend">
          <i class="el-icon-top" v-if="customerTrend > 0"></i>
          <i class="el-icon-bottom" v-else-if="customerTrend < 0"></i>
          <span :class="{'trend-up': customerTrend > 0, 'trend-down': customerTrend < 0}">{{ Math.abs(customerTrend) }}%</span>
        </div>
        <div class="stat-layout">
          <div class="stat-icon-wrapper">
            <i class="el-icon-user"></i>
          </div>
          <div class="stat-content">
            <div class="stat-title">客户总数</div>
            <div class="stat-value">{{ customerTotal | formatNumber }}</div>
          </div>
        </div>
        <div class="stat-progress">
          <div class="progress-bar" :style="{width: customerProgressPercent + '%'}"></div>
        </div>
      </div>

      <!-- 债权转让数量 Card -->
      <div class="stat-card stat-green animate__animated animate__fadeInUp" style="animation-delay: 0.1s">
        <div class="stat-trend">
          <i class="el-icon-top" v-if="debtTransferTrend > 0"></i>
          <i class="el-icon-bottom" v-else-if="debtTransferTrend < 0"></i>
          <span :class="{'trend-up': debtTransferTrend > 0, 'trend-down': debtTransferTrend < 0}">{{ Math.abs(debtTransferTrend) }}%</span>
        </div>
        <div class="stat-layout">
          <div class="stat-icon-wrapper">
            <i class="el-icon-sold-out"></i>
          </div>
          <div class="stat-content">
            <div class="stat-title">债权转让数量</div>
            <div class="stat-value">{{ debtTransferTotal | formatNumber }}</div>
          </div>
        </div>
        <div class="stat-progress">
          <div class="progress-bar" :style="{width: debtTransferProgressPercent + '%'}"></div>
        </div>
      </div>

      <!-- 风险委托数量 Card -->
      <div class="stat-card stat-orange animate__animated animate__fadeInUp" style="animation-delay: 0.2s">
        <div class="stat-trend">
          <i class="el-icon-top" v-if="riskEntrustTrend > 0"></i>
          <i class="el-icon-bottom" v-else-if="riskEntrustTrend < 0"></i>
          <span :class="{'trend-up': riskEntrustTrend > 0, 'trend-down': riskEntrustTrend < 0}">{{ Math.abs(riskEntrustTrend) }}%</span>
        </div>
        <div class="stat-layout">
          <div class="stat-icon-wrapper">
            <i class="el-icon-warning"></i>
          </div>
          <div class="stat-content">
            <div class="stat-title">风险委托数量</div>
            <div class="stat-value">{{ riskEntrustTotal | formatNumber }}</div>
          </div>
        </div>
        <div class="stat-progress">
          <div class="progress-bar" :style="{width: riskEntrustProgressPercent + '%'}"></div>
        </div>
      </div>

      <!-- 合同信息数量 Card -->
      <div class="stat-card stat-purple animate__animated animate__fadeInUp" style="animation-delay: 0.3s">
        <div class="stat-trend">
          <i class="el-icon-top" v-if="contractTrend > 0"></i>
          <i class="el-icon-bottom" v-else-if="contractTrend < 0"></i>
          <span :class="{'trend-up': contractTrend > 0, 'trend-down': contractTrend < 0}">{{ Math.abs(contractTrend) }}%</span>
        </div>
        <div class="stat-layout">
          <div class="stat-icon-wrapper">
            <i class="el-icon-document"></i>
          </div>
          <div class="stat-content">
            <div class="stat-title">合同信息数量</div>
            <div class="stat-value">{{ contractTotal | formatNumber }}</div>
          </div>
        </div>
        <div class="stat-progress">
          <div class="progress-bar" :style="{width: contractProgressPercent + '%'}"></div>
        </div>
      </div>
    </div>

    <!-- Charts Section -->
    <div class="charts-grid">
      <!-- Monthly Trend Chart -->
      <div class="chart-card animate__animated animate__fadeInUp" style="animation-delay: 0.4s">
        <div class="card-header">
          <h3>月度趋势分析</h3>
          <div class="card-actions">
            <el-select v-model="selectedTrendMetric" size="small" placeholder="选择指标">
              <el-option label="客户数量" value="customer"></el-option>
              <el-option label="债权转让" value="debt"></el-option>
              <el-option label="风险委托" value="risk"></el-option>
              <el-option label="合同信息" value="contract"></el-option>
            </el-select>
          </div>
        </div>
        <div class="chart-container">
          <div ref="trendChart" class="echarts-container"></div>
        </div>
      </div>

      <!-- Distribution Pie Chart -->
      <div class="chart-card animate__animated animate__fadeInUp" style="animation-delay: 0.5s">
        <div class="card-header">
          <h3>业务分布占比</h3>
          <div class="card-actions">
            <el-radio-group v-model="distributionView" size="small">
              <el-radio-button label="percent">百分比</el-radio-button>
              <el-radio-button label="amount">数量</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div class="chart-container">
          <div ref="pieChart" class="echarts-container"></div>
        </div>
      </div>
    </div>

    <!-- Recent Activity Section -->
    <div class="recent-activity animate__animated animate__fadeInUp" style="animation-delay: 0.6s">
      <div class="card-header">
        <h3>最近活动</h3>
        <el-button type="text" icon="el-icon-more" class="more-btn"></el-button>
      </div>
      <el-table :data="recentActivities" style="width: 100%" size="small" :show-header="false" :header-row-class-name="'hidden-header'">
        <el-table-column width="50">
          <template slot-scope="scope">
            <el-avatar :size="32" :icon="scope.row.icon" :style="{backgroundColor: scope.row.color}"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="title">
          <template slot-scope="scope">
            <div class="activity-content">
              <div class="activity-title">{{ scope.row.title }}</div>
              <div class="activity-desc">{{ scope.row.description }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="120" align="right">
          <template slot-scope="scope">
            <span class="activity-time">{{ scope.row.time }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { listBankCustomerCases } from '@/api/system/cases'
import { listInformation } from '@/api/system/information'
import { listBusiness } from '@/api/system/business'
import { listInfo } from '@/api/system/info'
import * as echarts from 'echarts'

export default {
  name: "Index",
  data() {
    return {
      // Stats data
      customerTotal: 0,
      debtTransferTotal: 0,
      riskEntrustTotal: 0,
      contractTotal: 0,
      
      // Trend percentages (would come from API in real implementation)
      customerTrend: 5.2,
      debtTransferTrend: 2.8,
      riskEntrustTrend: -1.5,
      contractTrend: 8.1,
      
      // Progress percentages
      customerProgressPercent: 85,
      debtTransferProgressPercent: 65,
      riskEntrustProgressPercent: 40,
      contractProgressPercent: 75,
      
      // Chart controls
      selectedTrendMetric: 'customer',
      distributionView: 'percent',
      dateRange: [new Date(new Date().setMonth(new Date().getMonth() - 1)), new Date()],
      
      // Charts instances
      trendChart: null,
      pieChart: null,
      
      // Demo recent activities
      recentActivities: [
        { 
          icon: 'el-icon-user', 
          color: '#4b8eff', 
          title: '新增客户', 
          description: '系统中新增3位客户信息',
          time: '10分钟前'
        },
        { 
          icon: 'el-icon-document', 
          color: '#9c27b0', 
          title: '合同签署', 
          description: '完成2份合同的签署流程',
          time: '2小时前'
        },
        { 
          icon: 'el-icon-warning', 
          color: '#ff9800', 
          title: '风险提醒', 
          description: '检测到1个风险委托需审核',
          time: '昨天'
        },
        { 
          icon: 'el-icon-sold-out', 
          color: '#4caf50', 
          title: '债权转让', 
          description: '完成债权转让交易',
          time: '2天前'
        }
      ]
    }
  },
  filters: {
    formatNumber(val) {
      if (typeof val === 'number') {
        return val.toLocaleString()
      }
      return val
    }
  },
  created() {
    this.fetchAllStats()
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
    })
    
    // Window resize listener for charts
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    // Clean up event listeners
    window.removeEventListener('resize', this.resizeCharts)
    
    // Dispose charts to prevent memory leaks
    if (this.trendChart) {
      this.trendChart.dispose()
    }
    if (this.pieChart) {
      this.pieChart.dispose()
    }
  },
  watch: {
    selectedTrendMetric() {
      this.updateTrendChart()
    },
    distributionView() {
      this.updatePieChart()
    }
  },
  methods: {
    fetchAllStats() {
      // 客户信息总数
      listBankCustomerCases({ pageNum: 1, pageSize: 1 }).then(res => {
        if (res && (res.code === 200 || res.total !== undefined)) {
          this.customerTotal = res.total || 0
        }
      })
      // 债权转让数量
      listInformation({ pageNum: 1, pageSize: 1 }).then(res => {
        if (res && (res.code === 200 || res.total !== undefined)) {
          this.debtTransferTotal = res.total || 0
        }
      })
      // 风险委托数量
      listBusiness({ pageNum: 1, pageSize: 1 }).then(res => {
        if (res && (res.code === 200 || res.total !== undefined)) {
          this.riskEntrustTotal = res.total || 0
        }
      })
      // 合同信息数量
      listInfo({ pageNum: 1, pageSize: 1 }).then(res => {
        if (res && (res.code === 200 || res.total !== undefined)) {
          this.contractTotal = res.total || 0
        }
      })
    },
    
    refreshData() {
      this.fetchAllStats()
      this.$message({
        message: '数据已刷新',
        type: 'success',
        duration: 2000
      })
      this.updateCharts()
    },
    
    // Initialize charts
    initCharts() {
      // Initialize trend chart
      this.trendChart = echarts.init(this.$refs.trendChart)
      this.updateTrendChart()
      
      // Initialize pie chart
      this.pieChart = echarts.init(this.$refs.pieChart)
      this.updatePieChart()
    },
    
    resizeCharts() {
      if (this.trendChart) {
        this.trendChart.resize()
      }
      if (this.pieChart) {
        this.pieChart.resize()
      }
    },
    
    updateCharts() {
      this.updateTrendChart()
      this.updatePieChart()
    },
    
    updateTrendChart() {
      // Sample data - in real app would come from API
      const months = ['1月', '2月', '3月', '4月', '5月', '6月']
      
      // Different datasets based on selected metric
      let data
      let color
      let title
      
      switch(this.selectedTrendMetric) {
        case 'customer':
          data = [120, 132, 145, 160, 178, 187]
          color = '#4b8eff'
          title = '客户数量'
          break
        case 'debt':
          data = [220, 240, 255, 265, 260, 278]
          color = '#4caf50'
          title = '债权转让'
          break
        case 'risk':
          data = [80, 95, 100, 112, 105, 98]
          color = '#ff9800'
          title = '风险委托'
          break
        case 'contract':
          data = [150, 160, 175, 190, 210, 225]
          color = '#9c27b0'
          title = '合同信息'
          break
      }
      
      const option = {
        title: {
          text: title + '趋势',
          left: 'center',
          show: false
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c}'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '8%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: months,
          axisLine: {
            lineStyle: {
              color: '#eaeaea'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#f5f5f5'
            }
          }
        },
        series: [
          {
            data: data,
            type: 'line',
            smooth: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            lineStyle: {
              width: 3,
              color: color
            },
            itemStyle: {
              color: color
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: color + '50' },
                { offset: 1, color: color + '10' }
              ])
            }
          }
        ]
      }
      
      this.trendChart.setOption(option)
    },
    
    updatePieChart() {
      // Use actual data totals for pie chart
      const data = [
        { value: this.customerTotal || 100, name: '客户数量', color: '#4b8eff' },
        { value: this.debtTransferTotal || 80, name: '债权转让', color: '#4caf50' },
        { value: this.riskEntrustTotal || 60, name: '风险委托', color: '#ff9800' },
        { value: this.contractTotal || 90, name: '合同信息', color: '#9c27b0' }
      ]
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: params => {
            const percent = Math.round(params.percent * 100) / 100 + '%'
            if (this.distributionView === 'percent') {
              return `${params.name}: ${percent}`
            } else {
              return `${params.name}: ${params.value.toLocaleString()} (${percent})`
            }
          }
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top: 'center',
          itemGap: 16,
          formatter: name => {
            const item = data.find(i => i.name === name)
            const percent = this.getPercentage(item.value, data.reduce((sum, i) => sum + i.value, 0))
            return `${name}  ${this.distributionView === 'percent' ? percent : item.value}`
          }
        },
        series: [
          {
            type: 'pie',
            radius: ['45%', '70%'],
            center: ['40%', '50%'],
            avoidLabelOverlap: false,
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data.map(item => ({
              value: item.value,
              name: item.name,
              itemStyle: {
                color: item.color
              }
            }))
          }
        ]
      }
      
      this.pieChart.setOption(option)
    },
    
    getPercentage(value, total) {
      if (!total) return '0%'
      return Math.round(value / total * 1000) / 10 + '%'
    }
  }
}
</script>

<style scoped lang="scss">
.dashboard-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);
}

// Dashboard Header
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  
  .dashboard-title {
    font-size: 22px;
    font-weight: 600;
    color: #333;
    margin: 0;
  }
  
  .dashboard-actions {
    display: flex;
    gap: 12px;
    
    .date-filter {
      width: 260px;
    }
  }
}

// Stats Grid
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.stat-card {
  position: relative;
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.04);
  padding: 20px;
  overflow: hidden;
  transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1),
              box-shadow 0.3s ease;
  border-left: 6px solid transparent;
  
  &:hover {
    transform: translateY(-6px);
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.08);
  }
  
  .stat-trend {
    position: absolute;
    top: 12px;
    right: 12px;
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    font-weight: 500;
    
    .trend-up {
      color: #4caf50;
    }
    
    .trend-down {
      color: #f44336;
    }
  }

  .stat-layout {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
  }
  
  &.stat-blue {
    border-left-color: #4b8eff;
    .stat-icon-wrapper { background: rgba(75, 142, 255, 0.1); }
    .stat-value { color: #4b8eff; }
    .progress-bar { background: #4b8eff; }
  }
  
  &.stat-green {
    border-left-color: #4caf50;
    .stat-icon-wrapper { background: rgba(76, 175, 80, 0.1); }
    .stat-value { color: #4caf50; }
    .progress-bar { background: #4caf50; }
  }
  
  &.stat-orange {
    border-left-color: #ff9800;
    .stat-icon-wrapper { background: rgba(255, 152, 0, 0.1); }
    .stat-value { color: #ff9800; }
    .progress-bar { background: #ff9800; }
  }
  
  &.stat-purple {
    border-left-color: #9c27b0;
    .stat-icon-wrapper { background: rgba(156, 39, 176, 0.1); }
    .stat-value { color: #9c27b0; }
    .progress-bar { background: #9c27b0; }
  }
}

.stat-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 52px;
  height: 52px;
  border-radius: 50%;
  margin-right: 18px;
  font-size: 24px;
  transition: all 0.3s ease;
  
  .stat-card:hover & {
    transform: scale(1.1) rotate(5deg);
  }
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #666;
  font-weight: 400;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 2.8rem;
  font-weight: 700;
  line-height: 1;
  letter-spacing: -1px;
}

.stat-progress {
  height: 4px;
  background: rgba(0,0,0,0.05);
  border-radius: 4px;
  overflow: hidden;
  width: 100%;
  
  .progress-bar {
    height: 100%;
    border-radius: 4px;
    transition: width 1s ease-in-out;
  }
}

// Charts Grid
.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 24px;
}

.chart-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  padding: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    h3 {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
      color: #333;
    }
    
    .card-actions {
      display: flex;
      gap: 8px;
    }
  }
  
  .chart-container {
    height: 320px;
    width: 100%;
    
    .echarts-container {
      width: 100%;
      height: 100%;
    }
  }
}

// Recent Activity
.recent-activity {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  padding: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    h3 {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
      color: #333;
    }
    
    .more-btn {
      color: #666;
      
      &:hover {
        color: #333;
      }
    }
  }
  
  .activity-content {
    .activity-title {
      font-weight: 500;
      color: #333;
      font-size: 14px;
      line-height: 1.3;
    }
    
    .activity-desc {
      color: #666;
      font-size: 13px;
      margin-top: 4px;
    }
  }
  
  .activity-time {
    color: #999;
    font-size: 12px;
  }
}

// Hidden table header
.hidden-header {
  display: none;
}

// Animations
.animate__animated {
  animation-duration: 0.6s;
}

.animate__fadeInUp {
  animation-name: fadeInUp;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translate3d(0, 30px, 0);
  }
  to {
    opacity: 1;
    transform: translate3d(0, 0, 0);
  }
}

// Responsive
@media (max-width: 1200px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 16px;
    gap: 16px;
  }
  
  .dashboard-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    
    .dashboard-actions {
      width: 100%;
      flex-wrap: wrap;
      
      .date-filter {
        width: 100%;
      }
    }
  }
  
  .stats-grid {
    gap: 16px;
  }
  
  .stat-card {
    padding: 16px;
    
    .stat-icon-wrapper {
      width: 45px;
      height: 45px;
      font-size: 20px;
      margin-right: 14px;
    }
    
    .stat-value {
      font-size: 2.2rem;
    }
  }
  
  .chart-card .chart-container {
    height: 260px;
  }
}
</style>

